import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../main.dart';
import '../../model/home/home_model.dart';
import '../../viewmodel/home/home_view_model.dart';
import '../../core/store/user_store.dart';
import '../../core/utils/navigate_to.dart';
import '../../config.dart';
import 'chat/chat_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  _HomePage createState() => _HomePage();
}

class _HomePage extends State<HomePage> with RouteAware {
  ContactListModel? contactList;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => _loadContacts());
  }

  Future<void> _loadContacts() async {
    final vm = context.read<HomeViewModel>();
    final list = await vm.searchContactList();
    setState(() {
      contactList = list;
    });
  }

  // RouteAware 相关
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    // 从其他页面返回（比如聊天页），刷新联系人列表
    _loadContacts();
  }

  @override
  Widget build(BuildContext context) {
    if (contactList == null) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _loadContacts,
        child: ListView.builder(
          itemCount: contactList!.contacts.length,
          itemBuilder: (context, index) {
            final contact = contactList!.contacts[index];
            final userInfoStr = Store().getString('login_data');
            final Map<String, dynamic> userInfo = jsonDecode(userInfoStr);

            return InkWell(
              onTap: () {
                navigateTo(ChatPage(
                  imId: contact.imId,
                  meAvatar: Config.baseUrl + userInfo['avatar'],
                  toAvatar: Config.baseUrl + contact.avatar,
                  name: contact.username,
                ));
              },
              child: Container(
                color: const Color(0xFFF6F0FA),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                child: Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Image.network(
                        Config.baseUrl + contact.avatar,
                        width: 48,
                        height: 48,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) => Container(
                          width: 48,
                          height: 48,
                          color: Colors.grey[300],
                          child: const Icon(Icons.person, color: Colors.white),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(contact.username,
                              style: const TextStyle(fontWeight: FontWeight.bold)),
                          const SizedBox(height: 4),
                          Text(contact.lastMessage?.content ?? '',
                              style: const TextStyle(fontSize: 12, color: Colors.grey)),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
